
package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();

        // TODO: [222024321072054/李欣雨]  根据请求的URL获取Handler
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            // 如果没有匹配的路由，使用 DefaultHandler 处理
            handler = config.getHandler("/");
        }

        if (handler != null) {
            handler.handle(request, response);
        } else {
            // TODO: [222024321072054/李欣雨]  如果连DefaultHandler都没有，返回500 Internal Server Error
            try {
                response.write("HTTP/1.1 500 Internal Server Error\r\n\r\n".getBytes());
            } catch (Exception ignore) { }
        }
    }
}